package com.wlr.study.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 *
 * @author HustleLr
 * @version 1.0.0
 * @date 2024/1/17 15:59
 * @describe LeetCode15
 */
public class LeetCode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int j = i + 1, k = nums.length - 1;
            if(nums[i] > 0) break;
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            while (j < k) {
                if (nums[i] + nums[k] + nums[j] > 0) {
                    while (i < k && nums[k] == nums[--k])
                        ;
                } else if (nums[i] + nums[k] + nums[j] < 0) {
                    while (i < k && nums[j] == nums[++j])
                        ;
                } else {
                    ArrayList<Integer> objects = new ArrayList<>();
                    objects.add(nums[i]);
                    objects.add(nums[j]);
                    objects.add(nums[k]);
                    result.add(objects);
                    while (j < k && nums[j] == nums[++j])
                        ;
                    while (j < k && nums[k] == nums[--k])
                        ;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        LeetCode15 leetCode15 = new LeetCode15();
        List<List<Integer>> lists = leetCode15.threeSum(new int[]{0, 0, 0});
        lists.forEach(System.out::println);
    }
}
